package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"perm-master/cache"
	"perm-master/models"
	"strconv"
	"time"
)

func CreateEssay(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")
	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不能为空",
		})
		return
	}
	data := models.Essay{
		Title:   title,
		Content: content,
		Author:  author,
	}
	err := models.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "发布失败",
		})
		return
	}
	redis_key := "essay_" + strconv.Itoa(int(data.ID))
	var essay models.Essay
	models.DB.Where("id=?", data.ID).Debug().First(&essay)
	jsonData, _ := json.Marshal(&essay)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "发布成功",
	})
	return
}
func Del(c *gin.Context) {
	id := c.Query("id")
	var essay models.Essay
	err := models.DB.Where("id=?", id).Delete(&essay).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "essay_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}
func ListEssay(c *gin.Context) {
	var essay []models.Essay
	err := models.DB.Debug().Find(&essay).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	redis_key := "list_"
	jsonData, _ := json.Marshal(&essay)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "查询成功",
		"essay": essay,
	})
	return
}
